package pers.hl.module_main.mine

import android.os.Bundle
import androidx.lifecycle.Observer
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import pers.hl.common.base.ext.showMessage
import pers.hl.lib_global.model.bean.Book
import pers.hl.module_main.common.BaseLibQuickAdapter
import pers.hl.module_main.common.ConfirmDialog
import pers.hl.module_main.common.SwipeMenuHelper
import pers.hl.module_main.search.BookAdapter

class CollectFragment : BaseBookListFragment(){

    override fun getTitle(): String {
        return "我的收藏"
    }

    override fun beforeSetAdapter() {
        mBinding.apply {
            val creator = SwipeMenuHelper.createRightItem(mContext, "取消收藏")
            recyclerView.setSwipeMenuCreator(creator)
            recyclerView.setOnItemMenuClickListener { menuBridge, adapterPosition ->

                // 任何操作必须先关闭菜单，否则可能出现Item菜单打开状态错乱。
                menuBridge.closeMenu()
                val item = mAdapter.getItem(adapterPosition) as Book
                ConfirmDialog.create(mContext)
                    .content("您确定要取消收藏吗？")
                    .setConfirmListener {
                        showMessage("取消收藏成功")
                        item.bookId?.let { mViewModel.unCollect(it).observe(this@CollectFragment, Observer {
                            mAdapter.removeAt(adapterPosition)
                        }) }
                    }
                    .setCancelListener {  }
                    .show()
            }
        }
    }

    override fun createAdapter(): BaseLibQuickAdapter<Book, BaseViewHolder> {
        return BookAdapter(mutableListOf())
    }

    override fun initData(savedInstanceState: Bundle?) {
        fetchMyCollect()
    }

    private fun fetchMyCollect() {
        mViewModel.fetchMyCollectBook().observe(this, Observer {
            if (it.isNullOrEmpty()) {
                mAdapter.setEmptyView()
            } else {
                mAdapter.setList(it)
            }
        })
    }
}